//
//  BuyyerMainViewController.m
//  SmartCoin
//
//  Created by apple on 2018/3/14.
//  Copyright © 2018年 Cynic. All rights reserved.
//

#import "BuyyerMainViewController.h"
#import "BuyyerHeaderTableViewCell.h"
#import "BuyyerListTableViewCell.h"
#import "DetailCashTableViewCell.h"
//#import "DetailBuyyerViewController.h"
#import "CashOutViewController.h"
//#import <SellerMineViewController.h>
#import "SellerMineViewController.h"
static NSString *BuyyerHeaderTableViewCellIndentifier = @"BuyyerHeaderTableViewCellIndentifier";
static NSString *BuyyerListTableViewCellIndentifier = @"BuyyerListTableViewCellIndentifier";
static NSString *DetailCashaTableViewCellIndentifier = @"DetailCashaTableViewCellIndentifier";
@interface BuyyerMainViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,retain)UITableView *mainView;
@property (nonatomic ,retain)UIView *segview;
@property (nonatomic ,retain)UIView *noticeView;//浮标
@property (nonatomic ,retain)UIButton *currentSeg;
@property (nonatomic ,assign)NSInteger currentSegNumber;
@property (nonatomic ,assign)CGFloat leftoffset;
@property (nonatomic, assign)CGFloat rightoffset;
@property (nonatomic ,assign)NSInteger leftPage;
@property (nonatomic ,assign)NSInteger rightPage;
@property (nonatomic ,retain)NSMutableArray *leftData;
@property (nonatomic ,retain)NSMutableArray *rightData;

@end

@implementation BuyyerMainViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = bggrayColor;
    [self viewLoad];
    _currentSegNumber = 0;
    [self dataloadWithSeg:_currentSegNumber withMore:YES];
    
    //    [self dataLoad];
    [self moneyDatarefresh];
}

-(void)moneyDatarefresh{
    NetWorkModel *netmodel = [[NetWorkModel alloc] init];
    WEAKSELF;
    netmodel.sendMessage = ^(NSString *result) {
        if ([result isEqual:@"success"]) {
            NSMutableDictionary *placeDic = [cxsingler.DicData mutableCopy];
            NSArray *keys = [placeDic allKeys];
            for (NSInteger index = 0; index < keys.count; index ++) {
                NSString *key = keys[index];
                [cxsingler.personData setObject:[weakSelf Nnll:placeDic[key] withPlace:@"--"] forKey:key];
            }
//            [weakSelf moneyRecheck];
            [weakSelf.mainView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
        }
        else{
            [SVProgressHUD showErrorWithStatus:result];
        }
    };
    [netmodel getUserMoneyinfoByUser:cxsingler.staffid];
}



-(void)viewLoad{
    [self dataReady];
    [self navigationLoad];
    [self mainViewLoad];
}

-(void)dataReady{
    _currentSegNumber = 0;
    _leftoffset = 0;
    _rightoffset = 0;
    _leftPage = 1;
    _rightPage = 1;
    _leftData = [NSMutableArray array];
//    _rightData = [NSMutableArray array];
}

-(void)navigationLoad{
    UIView *navigationBG = [[UIView alloc] initWithFrame:CGRectMake(0, cxsingler.topdis -  cxsingler.navitop, cx_wid, 132 + 20)];
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.frame = CGRectMake(0, 0, cx_wid, 152);
    layer.colors = @[(id)[CXSinglerModel colorWithHex:@"#FF7F5A" alpha:1].CGColor,(id)[CXSinglerModel colorWithHex:@"#FE4438" alpha:1].CGColor];
    layer.startPoint = CGPointMake(0, 0);
    layer.endPoint = CGPointMake(1, 0);
    [navigationBG.layer addSublayer:layer];
    
    UIButton *popButton = [[UIButton alloc] initWithFrame:CGRectMake(0, cxsingler.topdis, 44, 44)];
    
    UIButton *centerBtn = [[UIButton alloc] initWithFrame:CGRectMake(44, cxsingler.topdis, cx_wid - 88, 44)];
    UIButton *operation = [[UIButton alloc] initWithFrame:CGRectMake(cx_wid - 12 - 66, cxsingler.topdis + 6, 66, 32)];
    operation.layer.cornerRadius = 16;
    operation.layer.borderWidth = 1;
    operation.layer.borderColor = [UIColor whiteColor].CGColor;
    [operation setTitle:@"提现" forState:UIControlStateNormal];
    operation.titleLabel.font = [UIFont systemFontOfSize:15];
    [operation addTarget:self action:@selector(operationTaped:) forControlEvents:UIControlEventTouchUpInside];
    centerBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [centerBtn setTitle:cxsingler.companyname forState:UIControlStateNormal];
    [popButton setImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [popButton addTarget:self action:@selector(popbtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:navigationBG];
    [self.view addSubview:centerBtn];
//    [navigationBG addSubview:operation];
    [self.view addSubview:popButton];
    //    [loginbtn.layer addSublayer:layer];
}


-(void)mainViewLoad{
    _mainView = [[UITableView alloc] initWithFrame:CGRectMake(0, cxsingler.topdis + 44, cx_wid, cx_hit - cxsingler.topdis - cxsingler.bottomdis - 44 )];
    _mainView.delegate = self;
    _mainView.dataSource = self;
    _mainView.estimatedRowHeight = 0;
    _mainView.backgroundColor = [UIColor clearColor];
    [_mainView registerClass:[BuyyerListTableViewCell class] forCellReuseIdentifier:BuyyerListTableViewCellIndentifier];
    [_mainView registerClass:[BuyyerHeaderTableViewCell class] forCellReuseIdentifier:BuyyerHeaderTableViewCellIndentifier];
    [_mainView registerClass:[DetailCashTableViewCell class] forCellReuseIdentifier:DetailCashaTableViewCellIndentifier];
    _mainView.separatorStyle = UITableViewCellSeparatorStyleNone;
    MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
        [self dataloadWithSeg:_currentSegNumber withMore:YES];
    }];
    [footer setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
    [footer setTitle:@"松开加载更多" forState:MJRefreshStatePulling];
    [footer setTitle:@"加载更多中……" forState:MJRefreshStateRefreshing];
    _mainView.mj_footer = footer;
    [self.view addSubview:_mainView];
}

-(void)dataloadWithSeg:(NSInteger)segNumber withMore:(BOOL)isMore{
    NetWorkModel *netmodel = [[NetWorkModel alloc] init];
    WEAKSELF;
    netmodel.sendMessage = ^(NSString *result) {
        [weakSelf.mainView.mj_footer endRefreshing];
        if ([result isEqual:@"success"]) {
            NSMutableArray *placelist = [cxsingler.ArraryData mutableCopy];
            if (placelist.count > 0) {
                for (NSDictionary *part in placelist) {
                    if (segNumber == 0) {
                        [weakSelf.leftData addObject:part];
                    }
                    else if (segNumber == 1){
                        [weakSelf.rightData addObject:part];
                    }
                }
                if (segNumber == 0) {
                    weakSelf.leftPage ++;
                }
                else if (segNumber == 1){
                    weakSelf.rightPage ++;
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (weakSelf.currentSegNumber == segNumber) {
                        [weakSelf.mainView reloadData];
                    }
                });
            }
        }
    };
    NSInteger page = _rightPage;
    if (segNumber == 0) {
        page = _leftPage;
        [netmodel getUserBonusListByUser:cxsingler.staffid withPage:page];
    }
    else{
        [netmodel getUserCashOutDetailListByUser:cxsingler.staffid withPage:page];
    }
    
}

#pragma mark--uitableview代理开始
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }
    else{
        return 44;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger sec = indexPath.section;
    if (sec == 0) {
        return 153 + 30 + 10;
    }
    if (_currentSegNumber == 0) {
        return 172;
    }
    else{
        return 133;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        if (!_segview) {
            _segview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cx_wid, 44)];
            UIView *layerview = [[UIView alloc] initWithFrame:CGRectMake(0, 42, cx_wid, 2)];
            layerview.backgroundColor = bggrayColor;
            
            NSArray *names = @[@"分红明细",@"提现明细"];
            for (NSInteger index = 0; index < 2; index ++) {
                UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(cx_wid / 2 * index, 0, cx_wid / 2, 44)];
                [button setTitle:names[index] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button setTitleColor:[CXSinglerModel colorWithHex:@"FE4438" alpha:1] forState:UIControlStateSelected];
                button.backgroundColor = [UIColor whiteColor];
                button.titleLabel.font = [UIFont systemFontOfSize:14];
                [button addTarget:self action:@selector(segtaped:) forControlEvents:UIControlEventTouchUpInside];
                [_segview addSubview:button];
                if (index == 0) {
                    _currentSeg = button;
                    _noticeView = [[UIView alloc] init];
                    _noticeView.bounds = CGRectMake(0, 0, cx_wid / 2 / 2.3, 2);
                    _noticeView.center = CGPointMake(cx_wid / 4, 43);
                    _noticeView.backgroundColor = [CXSinglerModel colorWithHex:@"FE4438" alpha:1];
                    button.selected = YES;
                    [_segview addSubview:_noticeView];
                    
                }
                else{
                    button.selected = NO;
                }
            }
            [_segview addSubview:layerview];
            [_segview bringSubviewToFront:_noticeView];
        }
        return _segview;
    }
    else{
        UIView *headerview = [[UIView alloc] initWithFrame:CGRectZero];
        return headerview;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    if (_currentSegNumber == 0) {
        return _leftData.count;
    }
    else{
        return _rightData.count;
    }
//    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    NSInteger sec = indexPath.section;
    if (sec == 0) {
        BuyyerHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:BuyyerHeaderTableViewCellIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        /**
         @property (nonatomic ,retain)UIButton *header;
         @property (nonatomic ,retain)UILabel *name;
         @property (nonatomic ,retain)UILabel *joblabel;
         @property (nonatomic ,retain)UILabel *idlabel;
         @property (nonatomic ,retain)UILabel *allMoney;
         @property (nonatomic ,retain)UILabel *outedMoney;
         @property (nonatomic ,retain)UILabel *canoutMoney;
         */
        [cell.header sd_setBackgroundImageWithURL:[NSURL URLWithString:cxsingler.personData[@"avatar"]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"logo1"]];
        cell.name.text = cxsingler.loginrequest[@"name"];
        cell.joblabel.text = cxsingler.jobname;
        cell.idlabel.text = cxsingler.personData[@"empno"];
        cell.canoutMoney.text = [NSString stringWithFormat:@"%.2lf",[cxsingler.personData[@"balance"] floatValue] / 100];
        cell.allMoney.text = [NSString stringWithFormat:@"%.2lf",[cxsingler.personData[@"bonusAmount"] floatValue] / 100];
        cell.outedMoney.text = [NSString stringWithFormat:@"%.2lf",[cxsingler.personData[@"withdrawalAmount"] floatValue] / 100];
        return cell;
    }
    else if(_currentSegNumber == 0){
        BuyyerListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:BuyyerListTableViewCellIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = bggrayColor;
        NSDictionary *partdic = _leftData[row];
        NSLog(@"set left cell");
        NSString *timestr = [self gettimeByInter:[[[NSString stringWithFormat:@"%@",partdic[@"createDate"]] substringWithRange:NSMakeRange(0, 10)] integerValue]];
        cell.timelabel.text = timestr;
        cell.idlabel.text = [NSString stringWithFormat:@"%@",partdic[@"orderNo"]];
        cell.allmoneylabel.text =  [NSString stringWithFormat:@"￥%.2lf(%ld积分)",[partdic[@"payAmount"] floatValue] / 100,[partdic[@"payIntegral"] integerValue]];
        cell.allRiselabel.text =  [NSString stringWithFormat:@"￥%.2lf",[partdic[@"bonusAmount"] floatValue] / 100];
        cell.myRiselabel.text = [NSString stringWithFormat:@"￥%.2lf(%.2lf%%)", [partdic[@"balance"] floatValue] / 100,[partdic[@"rate"] floatValue]];
        /**
         @property (nonatomic ,retain)UILabel *timelabel;
         @property (nonatomic ,retain)UILabel *idlabel;
         @property (nonatomic ,retain)UILabel *allmoneylabel;
         @property (nonatomic ,retain)UILabel *allRiselabel;
         @property (nonatomic ,retain)UILabel *myRiselabel;
         */
//        cell.
        return cell;
    }
    else{
        DetailCashTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:DetailCashaTableViewCellIndentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = bggrayColor;
        NSDictionary *partdic = _rightData[row];
        NSLog(@"set right cell");
        NSString *timestr = [self gettimeByInter:[[[NSString stringWithFormat:@"%@",partdic[@"createDate"]] substringWithRange:NSMakeRange(0, 10)] integerValue]];
        cell.timelabel.text = timestr;
        NSInteger status = [partdic[@"state"] integerValue];
        NSString *imagename = @"";
        if (status == 0) {
//            cell.statusBtn.selected = YES;
            imagename = @"tag_not_audit";
        }
        else if(status == 1){
            imagename = @"tag_pass";
        }
        else if(status == 2){
            imagename = @"tag_review";
        }
        else if (status == 3){
            imagename = @"tag_deal";
        }
        else if (status == -1){
            imagename = @"tag_no_pass";
        }
        else if (status == -2){
            imagename = @"tag_fail";
        }
        [cell.statusBtn setImage:[UIImage imageNamed:imagename] forState:UIControlStateNormal];
        cell.cashMoneylabel.text = [NSString stringWithFormat:@"%.2lf",[partdic[@"amount"] floatValue] / 100];
        CGFloat waymoney = [[self Nnll:partdic[@"handlingFee"]                                                                                                                                                                                                withPlace:@"0"] floatValue] / 100 * [partdic[@"amount"] floatValue] / 100;
        NSString *price = [NSString stringWithFormat:@"(手续费:%.2lf)",waymoney];
        NSString *startstr = [NSString stringWithFormat:@"%.2lf",[[self Nnll:partdic[@"amount"]                                                                                                                                                                                                withPlace:@"0"] floatValue] / 100 - waymoney];
        NSMutableAttributedString *getcashStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@",startstr,price]];
        
        [getcashStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, getcashStr.length)];
        [getcashStr addAttribute:NSForegroundColorAttributeName value:[CXSinglerModel colorWithHex:@"2734fb" alpha:1] range:NSMakeRange(startstr.length, price.length)];
        cell.getCashlabel.attributedText = getcashStr ;
        cell.idlabel.text = [NSString stringWithFormat:@"%@",partdic[@"orderNo"]];
        /**
         @property (nonatomic ,retain)UILabel *timelabel;
         @property (nonatomic ,retain)UILabel *cashMoneylabel;
         @property (nonatomic ,retain)UILabel *getCashlabel;
         @property (nonatomic ,retain)UILabel *idlabel;
         @property (nonatomic ,retain)UIButton *statusBtn;
         */
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_currentSegNumber == 0) {
        //    SellerMineViewController *nextVC = [[SellerMineViewController alloc] init];
        //    [self.navigationController pushViewController:nextVC animated:YES];
    }
}
#pragma mark--uitableview代理结束

#pragma mark--点击
-(void)segtaped:(UIButton *)sender{
    if ([_currentSeg isEqual:sender]) {
        
    }
    else{
        self.view.userInteractionEnabled = NO;
        _currentSeg.selected = NO;
        sender.selected = YES;
        _currentSeg = sender;
        if ([_currentSeg.titleLabel.text isEqual:@"分红明细"]) {
            _currentSegNumber = 0;
            _rightoffset = _mainView.contentOffset.y;
            [_mainView setContentOffset:CGPointMake(0, _leftoffset)];
        }
        else{
            _currentSegNumber = 1;
            if (!_rightData) {
                _rightData = [NSMutableArray array];
                [self dataloadWithSeg:_currentSegNumber withMore:YES];
            }
            _leftoffset = _mainView.contentOffset.y;
            [_mainView setContentOffset:CGPointMake(0, _rightoffset)];
        }
        [_mainView reloadData];
        //        [UIView animateWithDuration:0.1 animations:^{
        //            _noticeView.center = CGPointMake(cx_wid / 4 * (1 + 2 * _currentSegNumber), 43);
        //        }];
        [UIView transitionWithView:self.view duration:0.1 options:UIViewAnimationOptionCurveLinear animations:^{
            _noticeView.center = CGPointMake(cx_wid / 4 * (1 + 2 * _currentSegNumber), 43);
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
        }];
    }
}

-(void)operationTaped:(UIButton *)sender{
    CashOutViewController *nextVC = [[CashOutViewController alloc] init];
    [self.navigationController pushViewController:nextVC animated:YES];
}

-(void)popbtn:(UIButton *)sender{
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
